#!/bin/bash
# REQUEST_FOR_LOG_TYPE_ARRAY=("Notification" "Pgyer")
# sh ${CommonFun_HomeDir_Absolute}/brances_info/brances_info_log/brances_info_log.sh -envInfoF "${Package_Environment_FILE_PATH}" --request-for-log-types "${REQUEST_FOR_LOG_TYPE_ARRAY[*]}" -comScriptHomeDir "${CommonFun_HomeDir_Absolute}" -resultSaveToJsonF "${TEST_DATA_RESULT_FILE_PATH}"
JQ_EXEC=`which jq`


exit_script() { # 退出脚本的方法，省去当某个步骤失败后，还去继续多余的执行其他操作
    exit 1
}


# 定义颜色常量
NC='\033[0m' # No Color
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'

# 当前【shell脚本】的工作目录
# $PWD代表获取当前路径，当cd后，$PWD也会跟着更新到新的cd路径。这个和在终端操作是一样的道理的
CurrentDIR_Script_Absolute="$( cd "$( dirname "$0" )" && pwd )"
#echo "CurrentDIR_Script_Absolute=${CurrentDIR_Script_Absolute}"
#CommonFun_HomeDir_Absolute=${CurrentDIR_Script_Absolute}/..
CommonFun_HomeDir_Absolute2=${CurrentDIR_Script_Absolute%/*} # 使用此方法可以避免路径上有..
CommonFun_HomeDir_Absolute=${CommonFun_HomeDir_Absolute2%/*} # 使用此方法可以避免路径上有..
# CommonFun_HomeDir_Absolute=${CurrentDIR_Script_Absolute}
# echo "CommonFun_HomeDir_Absolute=${CommonFun_HomeDir_Absolute} ✅"

qscript_path_get_filepath="${CommonFun_HomeDir_Absolute}/qscript_path_get.sh"
qbase_update_json_file_singleString_script_path="$(sh ${qscript_path_get_filepath} qbase update_json_file_singleString)"
qbase_function_log_msg_script_path="$(sh ${qscript_path_get_filepath} qbase function_log_msg)"
source $qbase_function_log_msg_script_path # 为了使用 logResultValueToJsonFile 、 logResultValueToJsonFile


get_branch_all_detail_info_script_path="$(sh ${qscript_path_get_filepath} qbase get20_branchMapsInfo_byHisJsonFile)"




function logSuccessMsg() {
    printf "${GREEN}$1${GREEN}\n${NC}"
}

function logMsg() {
    printf "$1\n${NC}"
}

function debug_log() {
    if [ "${isRelease}" == true ]; then
        echo "$1"
    fi
}


# 获取Map指定key值的branch数组信息
function getBranchsLogFromMapAndKey() {
    while [ -n "$1" ]
    do
            case "$1" in
                    -branchRootMap|--branchRootMap) branchRootMap=$2; shift 2;;
                    -branchsKey|--branchsKey) branchsKey=$2; shift 2;;
                    -showCategoryName|--show-category-name) showCategoryName=$2; shift 2;;
                    -showFlag|--show-branchLog-Flag) showBranchLogFlag=$2; shift 2;;
                    -showName|--show-branchName) showBranchName=$2; shift 2;;
                    -showTime|--show-branchTimeLog) showBranchTimeLog=$2; shift 2;;
                    -showAt|--show-branchAtLog) showBranchAtLog=$2; shift 2;;
                    -showTable|--show-branchTable) showBranchTable=$2; shift 2;;
                    -shouldMD|--should-markdown) shouldMarkdown=$2; shift 2;;
                    -resultSaveToJsonF|--result-save-to-json-file-path) RESULT_SALE_TO_JSON_FILE_PATH=$2; shift 2;; # 为简化换行符的保真(而不是显示成换行,导致后面计算数组个数麻烦),将结果保存在的JSON文件
                    -resultBranchKey|--result-branch-array-save-by-key) RESULT_BRANCH_ARRAY_SALE_BY_KEY=$2; shift 2;;   # 分支branch元素数组结果,用什么key保存到上述文件
                    -resultCategoryKey|--result-category-array-save-by-key) RESULT_CATEGORY_ARRAY_SALE_BY_KEY=$2; shift 2;;   # 分类category元素数组结果,用什么key保存到上述文件
                    -resultFullKey|--result-full-string-save-by-key) RESULT_FULL_STRING_SALE_BY_KEY=$2; shift 2;;   # 总字符串结果,用什么key保存到上述文件
                    --) break ;;
                    *) echo $1,$2; break ;;
            esac
    done
    
    #echo "branchsKey=${branchsKey}"
    
    #branchMapArray=$(echo ${branchRootMap} | ${JQ_EXEC} -r '.online_brances') # -r 去除字符串引号
    # [如何在shell中使用jq cmd变量](https://www.5axxw.com/questions/content/5ucfc4)
    branchMapArray=$(echo ${branchRootMap} | jq -r --arg branchsKey "$branchsKey" '.[$branchsKey]')
    #echo ">>>>>>>>>>>>>>>>branchMapArray=${branchMapArray}"
    
    # debug_log "正在引入方法文件(为了使用 getAllBranchLogString)：source ${branchs_info_log_common_file_Absolute} -commonFunHomeDir \"${bulidScriptCommon_dir_Absolute}\" --branch-info-json-file \"${Develop_Branchs_FILE_PATH}\""
    # source ${branchs_info_log_common_file_Absolute} -commonFunHomeDir "${bulidScriptCommon_dir_Absolute}" --branch-info-json-file "${Develop_Branchs_FILE_PATH}"
    # getAllBranchLogString -branchMaps "${branchMapArray}" -showCategoryName "${showCategoryName}" -showFlag "${showBranchLogFlag}" -showName "${showBranchName}" -showTime "${showBranchTimeLog}" -showAt "${showBranchAtLog}" -showTable "${showBranchTable}" -shouldMD "${shouldMarkdown}" -resultSaveToJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}" -resultBranchKey "${RESULT_BRANCH_ARRAY_SALE_BY_KEY}" -resultCategoryKey "${RESULT_CATEGORY_ARRAY_SALE_BY_KEY}" -resultFullKey "${RESULT_FULL_STRING_SALE_BY_KEY}"

    # buildContainBranchMaps="[]"
    buildContainBranchMaps=${branchMapArray}
    debug_log "${YELLOW}正在执行命令(进行历史分类4):《 ${BLUE}sh $get_branch_all_detail_info_script_path -branchMapsInJsonF \"${History_Versions_FILE_PATH}\" -branchMapsInKey \".history_versions[0].online_brances\" -showCategoryName \"${showCategoryName}\" -showFlag \"${showBranchLogFlag}\" -showName \"${showBranchName}\" -showTime \"${showBranchTimeLog}\" -showAt \"${showBranchAtLog}\" -showTable \"${showBranchTable}\" -shouldMD \"${shouldMarkdown}\" -resultSaveToJsonF \"${RESULT_SALE_TO_JSON_FILE_PATH}\" -resultBranchKey \"${RESULT_BRANCH_ARRAY_SALE_BY_KEY}\" -resultCategoryKey \"${RESULT_CATEGORY_ARRAY_SALE_BY_KEY}\" -resultFullKey \"${RESULT_FULL_STRING_SALE_BY_KEY}\" ${YELLOW}》${NC}"
    sh $get_branch_all_detail_info_script_path -branchMapsInJsonF "${History_Versions_FILE_PATH}" -branchMapsInKey ".history_versions[0].online_brances" -showCategoryName "${showCategoryName}" -showFlag "${showBranchLogFlag}" -showName "${showBranchName}" -showTime "${showBranchTimeLog}" -showAt "${showBranchAtLog}" -showTable "${showBranchTable}" -shouldMD "${shouldMarkdown}" -resultSaveToJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}" -resultBranchKey "${RESULT_BRANCH_ARRAY_SALE_BY_KEY}" -resultCategoryKey "${RESULT_CATEGORY_ARRAY_SALE_BY_KEY}" -resultFullKey "${RESULT_FULL_STRING_SALE_BY_KEY}"
    if [ $? != 0 ]; then
        return 1
    fi
}


# 获取上个线上版本的上线及所含功能分支的信息
while [ -n "$1" ]
do
    case "$1" in
        -historyVersionJsonF|--history-version-json-file) History_Versions_FILE_PATH=$2; shift 2;;
        -branchLogFor|--branchLogFor) branchLogFor=$2; shift 2;;
        -pn|--package-default-network) PackageNetworkType=$2; shift 2;;
        # -shouldMD|--should-markdown) shouldMarkdownLastOnline=$2; shift 2;;
        -resultSaveToJsonF|--result-save-to-json-file-path) RESULT_SALE_TO_JSON_FILE_PATH=$2; shift 2;; # 为简化换行符的保真(而不是显示成换行,导致后面计算数组个数麻烦),将结果保存在的JSON文件
        --) break ;;
        *) echo $1,$2; break ;;
    esac
done

if [ ! -f "${History_Versions_FILE_PATH}" ]; then
    echo "❌Error:您之前保存本次打包前的历史版本信息分支的History_Versions_FILE_PATH=${History_Versions_FILE_PATH} 中未设置或不存在，请先检查设置"
    exit 1
fi

if [ ! -f "${RESULT_SALE_TO_JSON_FILE_PATH}" ]; then
    echo "❌Error:您即将用来保存本次打包的当前分支信息结果的文件RESULT_SALE_TO_JSON_FILE_PATH=${RESULT_SALE_TO_JSON_FILE_PATH} 中未设置或不存在，请先检查设置"
    exit 1
fi

if [ -z "${PackageNetworkType}" ]; then
    echo "❌Error:您未设置 -pn|--package-default-network,请先检查设置"
    exit 1
fi

if [ "${branchLogFor}" == "Notification" ]; then
    echo "💡 正获取显示在到【企业微信】上的【上次打包】信息"
    showBranchLogFlag='false'
    showBranchName='false'
    showBranchTimeLog='only_last'
    showBranchAtLog='false'
    showBranchTable='false'
    showCategoryName='false' # 已上线的，分支类型都不显示
elif [ "${branchLogFor}" == "Pgyer" ]; then
    echo "💡 正获取显示在到【蒲公英】上的【上次打包】信息"
    if [ "${PackageNetworkType}" == "product" ]; then
        showBranchLogFlag='false'
        showBranchName='false'
        showBranchTimeLog='none'
        showBranchAtLog='false'
        showBranchTable='false'
        showCategoryName='false' # 已上线的，分支类型都不显示
    else
        showBranchLogFlag='false'
        showBranchName='false'
        showBranchTimeLog='only_last'
        showBranchAtLog='false'
        showBranchTable='false'
        showCategoryName='false' # 已上线的，分支类型都不显示
    fi
else
    echo "$FUNCNAME ❌获取上个线上版本的上线及所含功能分支的信息的日志类型入参错误:branchLogFor=${branchLogFor}，请检查"
    exit 1
fi

lastOnlineVersionLogStringResult=""

lastOnlineHeaderString="上个线上版本分支信息："
lastOnlineVersionLogStringResult+="${lastOnlineHeaderString}"

# fileValue_origin_withDoubleQuote=${Escape_LAST_BRANCH_ARRAY_STRING}
# #echo "======fileValue_origin_withDoubleQuote=${fileValue_origin_withDoubleQuote}"
# echo "======fileValue_origin_withDoubleQuote_echo=${fileValue_origin_withDoubleQuote//\\n/\\\\n}" # 这里转义换行符只是为了 echo 显示而已，没其他用处
# fileValue_origin_noDoubleQuote=${fileValue_origin_withDoubleQuote: 1:${#fileValue_origin_withDoubleQuote}-2}
# #echo "======fileValue_origin_noDoubleQuote=${fileValue_origin_noDoubleQuote}"
# echo "======fileValue_origin_noDoubleQuote_echo=${fileValue_origin_noDoubleQuote//\\n/\\\\n}" # 这里转义换行符只是为了 echo 显示而已，没其他用处
# Escape_LAST_BRANCH_ARRAY_STRING=${fileValue_origin_noDoubleQuote}



RESULT_FULL_LASTONLINE_STRING_SALE_BY_KEY="branch_info_result.${branchLogFor}.lastOnline.full"
if [ ! -f "${History_Versions_FILE_PATH}" ];then
    EMPTY_FULL_LASTONLINE_STRING="warning: no any history branchs info"
    lastOnlineVersionLogStringResult+="${EMPTY_FULL_LASTONLINE_STRING}"
    updateBranchResultFileKeyValue "${RESULT_SALE_TO_JSON_FILE_PATH}" "${RESULT_FULL_LASTONLINE_STRING_SALE_BY_KEY}" "${EMPTY_FULL_LASTONLINE_STRING}"
else
    lastOnlineVersionMapString=$(cat ${History_Versions_FILE_PATH} | ${JQ_EXEC} -r '.history_versions[0]' ) # -r 去除字符串引号
    lastOnlineVersionTimeString=$(echo ${lastOnlineVersionMapString} | ${JQ_EXEC} -r '.online_time') # -r 去除字符串引号

    RESULT_BRANCH_ARRAY_LASTONLINE_SALE_BY_KEY="branch_info_result.${branchLogFor}.lastOnline.branch"
    RESULT_CATEGORY_ARRAY_LASTONLINE_SALE_BY_KEY="branch_info_result.${branchLogFor}.lastOnline.category"
    debug_log "正在执行命令(获取上次版本信息):《 getBranchsLogFromMapAndKey -branchRootMap \"${lastOnlineVersionMapString}\" -branchsKey \"online_brances\" -showCategoryName \"${showCategoryName}\" -showFlag \"${showBranchLogFlag}\" -showName \"${showBranchName}\" -showTime \"${showBranchTimeLog}\" -showAt \"${showBranchAtLog}\" -showTable \"${showBranchTable}\" -shouldMD \"${shouldMarkdownLastOnline}\" -resultSaveToJsonF \"${RESULT_SALE_TO_JSON_FILE_PATH}\" -resultBranchKey \"${RESULT_BRANCH_ARRAY_LASTONLINE_SALE_BY_KEY}\" -resultCategoryKey \"${RESULT_CATEGORY_ARRAY_LASTONLINE_SALE_BY_KEY}\" -resultFullKey \"${RESULT_FULL_LASTONLINE_STRING_SALE_BY_KEY}\" 》"
    getBranchsLogFromMapAndKey -branchRootMap "${lastOnlineVersionMapString}" -branchsKey "online_brances" -showCategoryName "${showCategoryName}" -showFlag "${showBranchLogFlag}" -showName "${showBranchName}" -showTime "${showBranchTimeLog}" -showAt "${showBranchAtLog}" -showTable "${showBranchTable}" -shouldMD "${shouldMarkdownLastOnline}" -resultSaveToJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}" -resultBranchKey "${RESULT_BRANCH_ARRAY_LASTONLINE_SALE_BY_KEY}" -resultCategoryKey "${RESULT_CATEGORY_ARRAY_LASTONLINE_SALE_BY_KEY}" -resultFullKey "${RESULT_FULL_LASTONLINE_STRING_SALE_BY_KEY}"
fi


# echo "============上个线上版本分支信息 lastOnlineVersionLogStringResult============\n${lastOnlineVersionLogStringResult}"
